// pagesDoctor/doctorLogin/index.js
import {
  Apilogin,
  ApiloginDoctor,
  ApiGetSet
} from "../../api/docIndex.js"
import {
  debounce
} from "../../utils/util"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btn_loading: false,
    options: {
      username: "",
      password: "",
    },
    navBarHeight: app.globalData.navBarHeight,
    menuRight: app.globalData.menuRight,
    menuBotton: app.globalData.menuBotton,
    menuTop: app.globalData.menuTop,
    menuHeight: app.globalData.menuHeight,
    menuWidth: app.globalData.menuWidth,
  },
  handleClick() {
    wx.navigateBack()
  },

  onInput(e) {
    const value = e.detail.value
    const type = e.currentTarget.dataset.type
    this.setData({
      [`options.${type}`]: value,
      [`error.${type}`]: "",
    })
  },



  submit: debounce(function () {
    /* wx.showModal({
      title: "是否确认使用张三证书登录？",
      success(res) {
        if (res.confirm) {
          this.setData({
            showpoup:true
          })
        }

      }
    }) */

    const error = {
      code: "",
      password: ""
    }
    let flag = false
    if (!this.data.options.username) {
      error.username = "请输入用户名"
      flag = true
    }
    if (!this.data.options.password) {
      error.password = "请输入密码"
      flag = true
    }
    if (flag) {
      this.setData({
        error
      })
      return
    }
    this.onLogin()
  }, 500, true),

  getSet(){
    ApiGetSet().then(res => {
      this.setData({
        getSet: res.data
      })
    })
  },
  onLogin() {
    wx.setEnable1v1Chat({
      enable: true
    })
    this.setData({
      btn_loading: true
    })
    Apilogin(this.data.options).then(res => {
      let userInfo = res.data.user
      app.setToken(res.data.token, res.data.user)
      wx.setStorageSync('loginType', "doctor")
      app.setUserInfo(res.data.user)
      if (res.data.user.openid == "") {
        wx.login({
          success: (res) => {
            ApiloginDoctor({
              code: res.code
            }).then(res => {
              userInfo.openid = res.data.openid
              app.setUserInfo(userInfo)
              wx.reLaunch({
                url: '/pagesDoctor/doctorIndex/index'
              })
            })
          },
        })
      } else {
        wx.reLaunch({
          url: '/pagesDoctor/doctorIndex/index'
        })
      }
    }).then(res => {
      app.setWebScoket()
    }).finally(_ => {
      this.setData({
        btn_loading: false
      })
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getSet()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})